//
//  YDOAGoodsApplyVC.swift
//  YDOAProduct
//
//  Created by 占益民 on 2017/11/24.
//  Copyright © 2017年 Allen. All rights reserved.
//

import UIKit

import HandyJSON
import Toaster

class YDOAGoodsApplyVC: UIViewController {

    @IBOutlet weak var mysegmentVC: UISegmentedControl!
    
    @IBOutlet weak var myTableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    
    var xType : String! = "1"
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    var type : Int! // 1 办公  0 月度新要求
    lazy var dataSource : NSMutableArray = NSMutableArray()
    var page : Int? = 1
    var refreshtype : Bool! = false // false 下拉刷新   true 上拉加载
    var isSearch : Bool! = false //false 不是搜索  true   是搜索

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.isHidden = false
        self.automaticallyAdjustsScrollViewInsets = false
        self.edgesForExtendedLayout = .init(rawValue: 0)
        if type == 1{
            title = "办公领用申请"
        }else{
            title = "月度需求申请"
        }

        
        //设置searchbar 的样式
        self.searchBar.showsCancelButton = true //显示取消按钮
        
        
        myTableView.register(UINib(nibName: "YDOAStockCell", bundle: nil), forCellReuseIdentifier: STOCKREUSEID)
        weak var weakSelf = self
        myTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            weakSelf?.page = 1
            weakSelf?.refreshtype = false
            weakSelf?.loadData()
        })
        myTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            weakSelf?.page = (weakSelf?.page!)! + 1
            weakSelf?.refreshtype = true
            weakSelf?.loadData()
        })
        //加载数据
        loadData()
        // Do any additional setup after loading the view.
    }

    
    //  segment   values changes
    @IBAction func segmentValueChange(_ sender: UISegmentedControl) {
        
        myTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
        if sender.selectedSegmentIndex == 0{
            //办公
            self.xType = "1"
            self.page = 1
            self.loadData()
        }else if sender.selectedSegmentIndex == 1{
            //劳保
            self.xType = "2"
            self.page = 1
            self.loadData()
        }else{
            //招待
            self.xType = "3"
            self.page = 1
            self.loadData()
        }
    }
    func loadData(){
        var urlStr : String! = ""
        if !self.isSearch {
            urlStr = String(format:GET_KUCUN_LIST,self.xType,self.page!)
        }else{
            urlStr = String(format:SEARCH_STOCK_LIST,searchBar.text!)
            YMLog.log(item: urlStr)
         
        }
        
        YMLog.log(item: urlStr)
        YMNetworkManager().getRequest(urlString: urlStr, params: nil, success: { (responser) in
            YMLog.log(item: responser)
            if responser["status"]?.int8Value == 1{
                let dataArr = responser["data"] as! NSArray
                if !self.refreshtype || self.page == 1{
                    self.dataSource.removeAllObjects()
                }
                for dict in dataArr {
                    guard let model = JSONDeserializer<YDOAStockModel>.deserializeFrom(dict: dict as? NSDictionary) else{ return }
                    self.dataSource.add(model)
                }
                self.myTableView.mj_header.endRefreshing()
                self.myTableView.mj_footer.endRefreshing()
                self.myTableView.reloadData()
            }else{
                Toast(text: (responser["message"] as! String), delay: 0, duration: 1.5).show()
                self.myTableView.mj_header.endRefreshing()
                self.myTableView.mj_footer.endRefreshing()
            }
            
        }) { (error) in
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


//MARK :  --  tableView  代理方法
extension YDOAGoodsApplyVC : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  self.dataSource.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 132
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: STOCKREUSEID) as? YDOAStockCell else { return YDOAStockCell() }
        cell.selectionStyle = .none
        cell.index = indexPath.row
        let model =  self.dataSource[indexPath.row] as? YDOAStockModel
        cell.type = 1 //申请界面进入
        if type == 1{
             cell.isApply = false
        }else{
            cell.isApply = true
        }
      
        cell.model = model
        weak var weakSelf =  self
        cell.callback = {(index : Int, type : Int) in
            //type 1 删除   2  修改
            let  vc = YDOARefuceResonVCViewController()
            vc.placeHolderStr = "请填写申请数量"
            vc.modalPresentationStyle = .overCurrentContext //模态视图的展现形式
            vc.view.backgroundColor = UIColor(white: 0.3, alpha: 0.7) //视图的背景颜色
            
            let userinfo = UserDefaults.standard.object(forKey: USERINFO) as! [String:AnyObject]
        
            let model  = self.dataSource[index] as? YDOAStockModel
            //填写申请数量
            vc.callBack = {(applyNum : String) in
                YMLog.log(item: userinfo)
//                let params = [
//                    "id":model?.id ?? "",
//                    "num":applyNum,
//                    "type":"0",
//                    "uid":userinfo["id"]!
//                    ] as [String : Any]
//                YMLog.log(item: params)
                
                //MARK:  注意这里要根据
                var urlStr = ""

                //办公用品申请
                if type == 1 {
                    YMLog.log(item: userinfo["id"]!)
                    let uid =  userinfo["id"]!
                    urlStr = String(format:PUSH_BANGONG,model?.id ?? "",uid as! CVarArg,applyNum)
                }else{
                    //月度需求申请 PUSH_YUEDU
                    let uid =  userinfo["id"]!
                    urlStr =  String(format:PUSH_YUEDU,model?.id ?? "",uid as! CVarArg,applyNum)
                    
                    //月度申请只能每月的25-30号之间申请
                    if !self.judegDateIsConform() {
                        Toast(text: "月度申请只能在25-30号申请", delay: 0, duration: 1.5).show()
                        return ;
                    }
                }
                YMLog.log(item: urlStr)
                YMNetworkManager().getRequest(urlString: urlStr, params: nil, success: { (responser) in
                    if responser["status"]?.int8Value == 1{
                        Toast(text: "申请成功", delay: 0, duration: 1.5).show()
                    }else{
                        Toast(text: responser["message"] as! String, delay: 0, duration: 1.5).show()
                    }
                }, failture: { (error) in
                    
                })
               
            }
            weakSelf?.present(vc, animated: true) {
                
            }
        }
        return cell
    }
    
    
}


extension YDOAGoodsApplyVC : UISearchBarDelegate {
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        //        searchBar.showsCancelButton = true //显示取消按钮
        return true
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        YMLog.log(item: "取消搜索")
        searchBar.text = ""
        view.endEditing(true)
        page = 1
        isSearch = false
       self.refreshtype = true
        loadData()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        //        searchBar.showsCancelButton = false //隐藏取消按钮
        view.endEditing(true)
        isSearch = true
        self.refreshtype = false
        loadData()
        YMLog.log(item: "开始搜索")
    }
    
    
}

extension YDOAGoodsApplyVC{
    //判断日期是否符合规范  25 - 30 号
    func judegDateIsConform() -> Bool {
        //获取代表公历的 NSCalendar 对象
        let  gregorian = NSCalendar(calendarIdentifier: .gregorian)
        //获取当前时间
        let dt = Date()
        //获取不同的时间段信息
//        guard let comp = gregorian?.components( NSCalendar.Unit.day ,  from: dt) as!  DateComponents else{return false}
        guard let comp = gregorian?.components(.day, from: dt) else { return false }
        YMLog.log(item: comp)
        
        YMLog.log(item: comp.day)
        if comp.day! > 25 && comp.day! < 30{
            return true
        }
        return false
    }
}




